<?php


namespace App\Repositories;


use App\Exceptions\BasicException;

class RewardItemRepository
{
    public function updateRewardItem($rewardItem)
    {
        if ($rewardItem['id'] == 0) {
            $where[] = ['name', '=', $rewardItem['name']];
            $where[] = ['active', 1];
            $oldItem = app('model_reward_item')->where($where)->first();
            if ($oldItem) {
                throw new BasicException(98001);
            }
            $newReward = app('model_reward_item')->create($rewardItem);
            if ($newReward) {
                return $newReward;
            }
            throw new BasicException(98001);
        }
        $where[] = ['id', '=', $rewardItem['id']];
        $newRewardItem = app('model_reward_item')->where($where)->update($rewardItem);
        if ($newRewardItem) {
            return $newRewardItem;
        }
        throw new BasicException(98001);
    }

    public function getRewardItemList($type, $page, $perPage)
    {
        $where[] = ['active', '=', 1];
        if ($type > 0) {
            $where[] = ['type', '=', $type];
        }
        $rewardItemList = app('model_reward_item')
            ->with(['reward_type:id,name'])
            ->where($where)->orderBy('id', 'asc')->paginate($perPage, ['*'], '', $page);
        if ($rewardItemList) {
            return $rewardItemList;
        }
        throw new BasicException(98001);
    }

    public function delewardItem($id)
    {
        $where[] = ['id', '=', $id];
        $rewardItem['active'] = 2;
        $rewardItemList = app('model_reward_item')->where($where)->update($rewardItem);;
        if ($rewardItemList) {
            return $rewardItemList;
        }
        throw new BasicException(98001);
    }
}
